package com.walle.ak47.commons.jaxrs.interceptor.monitor;


import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.apache.log4j.Logger;

public class PerformanceStopInterceptor extends AbstractPhaseInterceptor<Message> implements PerformanceProtocol {
	protected static final Logger LOG = Logger.getLogger(PerformanceStopInterceptor.class);
	
	public PerformanceStopInterceptor() {
		super(Phase.PRE_STREAM);
	}

	public void handleMessage(Message message) throws Fault {
		Long setupMills = (Long) message.getExchange().get(PerformanceStartInterceptor.SETUP_MILLSCONDS);
		String uri = (String) message.getExchange().get(PerformanceStartInterceptor.REQUEST_URI);
		if (setupMills != null && uri != null ) {
			long val = System.currentTimeMillis() - setupMills.longValue();
			Performance p = map.get(uri);
			if (p == null) {
				p = new Performance();
			}
			p.incr(val);
			map.put(uri, p);
			
			if (LOG.isDebugEnabled()) LOG.debug("接口 " + uri + " 耗时 : " + val + " ms.");
		}
	}

}
